#include"List.h"

int list_ctor   (list_t* List)
{
    List->firstNode = 0;
    List->lastNode = 0;
}
node* newNode()
{
    node* n =(node*) calloc(1, sizeof(node));
    return n;
}
int list_insertA(list_t* List, node* Node , char value[])
{
    assert(List);
    if (list_ok(List) && List)
        return list_error(List, LIST_DAMAGED);

    node* newN = newNode();
    strcpy(newN->value, value);


    if (Node)
    {
        if(Node->next)
        {
            newN->next = Node->next;
            Node->next->prev = newN;
        }
        else
            List->lastNode = newN;
        Node->next = newN;
    }
    else
    {
        List->firstNode = newN;
        List->lastNode  = newN;
    }
    newN-> prev = Node;
    //now change list_t length
    List->length++;
    //list_dump(List);
    return 0;
}
int list_insertB(list_t* List, node* Node , char value[])
{
    assert(List);
    if (list_ok(List) && List)
        return list_error(List, LIST_DAMAGED);

    node* newN = newNode();
    strcpy(newN->value, value);

    if(Node)
    {
        if(Node->prev)
        {
            Node->prev->next = newN;
            newN->prev = Node->prev;
        }
        else
            List->firstNode = newN;
        Node->prev = newN;
    }
    else
    {
        List->firstNode = newN;
        List->lastNode  = newN;
    }
    newN->next = Node;

    List->length++;
}


int list_error(list_t* List, int err)
{
    //list_dump()
    assert(List);
    switch(err)
    {
        case LIST_DAMAGED:
            printf("\nSomething wrong with list_t variable\n");
            list_dump(List);
            return LIST_DAMAGED;
            break;
        case LIST_NULLPTR:
            printf("\nGot NULL pointer.\n");
            abort();
            break;
        case LIST_LENGTH:
            printf("Length of list_t less than 0");
            return LIST_LENGTH;
        default:
            return err;
            break;
    }
    return 0;
}

int list_ok(list_t* List)
{
    if(List)
    {
        if(List->length < 0)
            return LIST_LENGTH;
    }
    else return LIST_NULLPTR;
    return 0;
}

void list_dump(list_t* List)
{
    int counter = 0;
    node* nextN = List->firstNode;
    printf("\nlist_ok(%d) lastNode: [%p] firstNode:[%p]\n", list_ok(List), List->lastNode, List->firstNode);
    if (!list_ok(List))
    {
        printf("List length: %d\n", List->length);
        do
        {
            printf("    %d)Node[%p]: value: <%s> previous: [%p] next: [%p]\n", counter, nextN, nextN->value, nextN->prev, nextN->next);
            nextN = nextN->next;
            counter++;
        } while(counter < List->length);
    }
}
